package com.cma.typhoon.web.realm;

import com.cma.model.db.SysRole;
import com.cma.model.db.SysUser;
import com.cma.model.db.TwUser;
import com.cma.service.SysRoleService;
import com.cma.service.SysUserService;
import com.cma.service.TwUserService;
import com.cma.typhoon.web.credentials.CustomCredentialMatcher;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.*;


public class StatelessRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    public StatelessRealm(){
        setName("statelessRealm");

    }
    public boolean supports(AuthenticationToken token) {
        //仅支持StatelessToken类型的Token
       // return token instanceof StatelessToken;
        //换成支持usernamePasswordToken
        return token instanceof UsernamePasswordToken;
    }

    /**
     * 初始化自定义的认证方法
     */
    @PostConstruct
    public void initCredentialsMatcher() {
        //该句作用是重写shiro的密码验证，让shiro用我自己的验证
        //setCredentialsMatcher(new CustomCredentialMatcher());
        setCredentialsMatcher(new HashedCredentialsMatcher("md5"));//md5加密
    }

    /**
     * 根据用户名获取该用户的角色和权限等信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //根据用户名查找角色，请根据需求实现
        String username = (String) principals.getPrimaryPrincipal();
        List<SysRole> roles=sysRoleService.findRoleByUserName(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String roleId="";
        if(roles!=null &&roles.size()>0){
            for(SysRole sysRole:roles){
                authorizationInfo.addRole(sysRole.getRoleName());//添加赋予角色
                if(roleId.length()>0){
                    roleId=roleId+","+sysRole.getId();
                }else{
                    roleId=sysRole.getId()+"";
                }
            }
        }
        // TODO 根据角色 获取权限
        if(roleId.length()>0){
            Set<String> perss = new HashSet<String>();
            // TODO 权限字符串 格式为: 权限名称:权限描述 每一个权限以逗号隔开
            String permission= sysUserService.getPermissionsByRoleIds(roleId);
            perss.add(permission);
            authorizationInfo.setStringPermissions(perss);
        }
       /* Set<String> perss = new HashSet<String>();
        perss.add("admin:*");
        authorizationInfo.setStringPermissions(perss);*/
        return authorizationInfo;
    }

    /**
     * 验证用户
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
      //  StatelessToken statelessToken = (StatelessToken) token;
        UsernamePasswordToken statelessToken=(UsernamePasswordToken)token;
        String username = statelessToken.getUsername();

        //根据用户名获取密钥 & salt
       SysUser user= sysUserService.findByName(username);
        if(user ==null){
            throw new UnknownAccountException();
        }
     //   TwUser user = twUserService.findByName(username);
      //  Object serverDigest = user.getPassword();

        //然后进行客户端消息摘要和服务器端消息摘要的匹配

        return new SimpleAuthenticationInfo(
                username,
                user.getPassword(),
                getName());

    }
}
